package com.example.japinhands.ui.screen

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.japinhands.JapViewModel
import com.example.japinhands.data.Sentence
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch

@Deprecated("Sentence is no longer separated.")
@OptIn(ExperimentalMaterial3Api::class, FlowPreview::class)
@Composable
fun NewSentenceScreen(
    viewModel: JapViewModel
) {
    val tag = "NewSentenceScreen"
    var sentenceText by remember {
        mutableStateOf(viewModel.sentenceLiveData.value?.content ?: "")
    }
    val coroutineScope = rememberCoroutineScope()
    val inputFlow = remember {
        MutableSharedFlow<Sentence>()
    }
    LaunchedEffect(Unit) {
        coroutineScope.launch {
            inputFlow
                .debounce(1000)
                .distinctUntilChanged()
                .collectLatest {
                    viewModel.saveSentence(it)
                }
        }
    }
    TextField(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        value = sentenceText,
        onValueChange = {
            sentenceText = it
            val sentence = Sentence(
                content = sentenceText
            )
            coroutineScope.launch {
                inputFlow.emit(sentence)
            }
        },
        label = { Text(text = "例句") }
    )
}